package com.qf.controller;

import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.recipes.locks.InterProcessMutex;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @author 千峰教育
 * @Company http://www.mobiletrain.org/
 * @Version 1.0
 */

@RestController
public class TestController {

    //1. 准备商品的库存
    public static Map<String,Integer> itemStock = new HashMap<>();

    //2. 准备商品的订单
    public static Map<String,Integer> itemOrder = new HashMap<>();

    static {
        itemStock.put("牙刷", 1000);
        itemOrder.put("牙刷", 0);
    }

    @Autowired
    CuratorFramework client;


    @RequestMapping("/kill")
    public String kill(String item) throws Exception {

        //创建zookeeper分布式锁

        InterProcessMutex lock = new InterProcessMutex(client, "/lock");
        try {
            //如果获取锁成功，执行业务代码
            if( lock.acquire(1, TimeUnit.SECONDS) ) {
                //减库存
                Integer stock = itemStock.get(item);
                if(stock <= 0){
                    return item +"卖完了 ---- " + item+"还剩下: " + itemStock.get(item)
                            + "，已卖" + item  + ":" + itemOrder.get(item);
                }

                Thread.sleep(100);
                //库存减一
                itemStock.put(item, stock - 1);

                //增加订单
                Thread.sleep(100);
                itemOrder.put(item, itemOrder.get(item) + 1);
            }
        } finally {
            //业务执行完成，则释放锁(删除创建的临时节点)
            lock.release();
        }



        return item+"还剩下: " + itemStock.get(item) + "，已卖" + item  + ":" + itemOrder.get(item);
    }

}
